package summerprojectFX.parser;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import summerprojectFX.model.Song;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;


public class PDFFile extends FileInputOutput{
	
	public PDFFile(File file){
		super(file);
	}

	@Override
	public Song read() {
		Song newSong = new Song();
		 try {
			PdfReader reader = new PdfReader(file.getAbsolutePath());
			int numberOfPages = reader.getNumberOfPages();
			String song = "";
			for(int i = 1; i <= numberOfPages; i++){
				song = song + PdfTextExtractor.getTextFromPage(reader, i) + "\n";
			}
			
			newSong = createSong(song);
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
		return newSong;
	}

	public void write(Song song, String fileName) {
		Rectangle pageSize = new Rectangle(0,0,1000,1500);
		Document document = new Document(pageSize);
		try {
		PdfWriter.getInstance(document, new FileOutputStream(new File(fileName)));
		document.open();
		
		
		String[] temp = song.getLyrics().split("\n");

		try{
		String[] temp1 = song.getTitle().split("\\(");
		document.add(new Paragraph(temp1[0]));
		}catch(Exception e){
			document.add(new Paragraph(song.getTitle()));
		}
		
		for(int i = 0; i < temp.length; i++)
			document.add(new Paragraph( temp[i].replaceAll("\\t", "      ")));
	   
		
		}
		catch(DocumentException de) {
		System.err.println(de.getMessage());
		}
		catch(IOException ioe) {
		System.err.println(ioe.getMessage());
		}
		document.close();
		}
		
	}

